const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	randomId,
} = require('./api-utils')
const {
	editMethod,
} = require('./api-button-methods-2x')
const {
	importTemplateHistory,
} = require('./api-utils-history-2x')

module.exports = {

	/**
	 * 打开模板列表对话框
	 * @return {[type]} [description]
	 */
	openTemplateListDialog(flag) {
		let {
			store,
			templateDialog,
			templateTree,
			templateTable,
		} = this
		if (!store.isLock) {
			$.messager.confirm({
				title: '提示',
				msg: '当前是非编辑模式！是否切换到编辑模式？',
				fn: (r) => {
					if (r) {
						editMethod.call(this)
					}
				}
			});
			return false
		}
		reqPost('/ult/template/list').then(list => {
			if (!list || list.length < 1) {
				templateDialog.dialog('open')
				store.isSave = false
				return false
			}
			let treeDataMap = {}
			for (let val of list) {
				let text = val.project_name ? `项目-${val.project_name}` : "自定义模板"
				treeDataMap[val.project_id] = treeDataMap[val.project_id] || {
					id: randomId(),
					text,
					state: 'open',
					children: [],
				}
				treeDataMap[val.project_id].children.push({
					id: randomId(),
					text: val.name,
					attributes: {
						templateId: val.id,
						template: val.template,
						module_api_id: val.module_api_id,
					},
				})
			}
			let treeData = Object.values(treeDataMap)
			let {
				id: selectNodeId,
				attributes,
			} = treeData[0].children[0]
			let templateData = attributes.template
			console.log('templateData', templateData)
			try {
				templateData = JSON.parse(templateData)
			} catch (e) {
				templateData = templateData || []
			}
			templateTree.tree('loadData', treeData)
			let selectNode = templateTree.tree('find', selectNodeId)
			templateTree.tree('select', selectNode.target)
			templateTable.treegrid('loadData', templateData)
			templateDialog.dialog('open')
			store._flag = flag
			store.isSave = false
		})
	},

	/**
	 * 导入模板数据
	 * @return {[type]} [description]
	 */
	importTemplateData() {
		let {
			store,
			templateDialog,
			templateTable,
			templateTree,
		} = this
		let flag = store._flag
		let paramsComp = this[`${flag}ParamsComp`]
		let templateData = templateTable.treegrid('getData')
		let treeSelected = templateTree.tree('getSelected')
		paramsComp.treegrid('loadData', templateData)
		let moduleId = store._currentCheckApiDetail && store._currentCheckApiDetail.id;
		importTemplateHistory.call(this, treeSelected.text, moduleId)
		templateDialog.dialog('close')
	},

	/**
	 * 加载模板数据
	 * @param  {[type]} node [description]
	 * @return {[type]}      [description]
	 */
	loadTemplateDetail(node) {
		let {
			store,
			templateTree,
			templateTable,
		} = this
		if (node.children || !node.attributes)
			return true
		let template = node.attributes.template
		try {
			template = JSON.parse(template)
		} catch (e) {
			template = Array.isArray(template) ? template : []
		}
		templateTable.treegrid('loadData', template)
	},

	/**
	 * 设置参数模板
	 * @param  {[type]} flag [description]
	 * @return {[type]}      [description]
	 */
	saveASTemplate(flag) {
		let {
			store,
		} = this
		let paramsComp = this[`${flag}ParamsComp`]
		let paramsData = paramsComp.treegrid('getData')
		if (paramsData.length < 1) {
			$.messager.alert({
				title: "提示",
				msg: '没有参数，无法生成模板！'
			})
			return false
		}
		let _currentCheckApiDetail = store._currentCheckApiDetail;
		// filterTemplate(paramsData)
		console.log('paramsData', paramsData)
		let name = `${flag == 'req'? '请求' : '响应'}_${store.projectName}_${_currentCheckApiDetail.name || _currentCheckApiDetail.text}`
		let description = `[${flag == 'req'? '请求参数' : '响应参数'}]生成模板->项目:[${store.projectName}]-接口:[${_currentCheckApiDetail.text}]`
		let template = JSON.stringify(paramsData)
		let project_id = store.projectId
		let module_api_id = `${flag}_${project_id}_${_currentCheckApiDetail.id}`
		let params = {
			name,
			description,
			template,
			project_id,
			module_api_id,
		}
		checkTemplate(params)
	},

}

/**
 * 模板remark不需要设置值
 * @param  {[type]} paramsData [description]
 * @return {[type]}            [description]
 */
function filterTemplate(paramsData) {
	for (let i = 0; i < paramsData.length; i++) {
		let param = paramsData[i]
		param.remark = ''
		if (param.children && param.children.length > 0)
			filterTemplate(param.children)
	}
}

/**
 * 检查模板是否存在
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
async function checkTemplate(params) {
	let {
		id,
	} = await reqPost('/ult/template/check', {
		module_api_id: params.module_api_id
	})
	if (!id) {
		return saveTemplate(params)
	}
	$.messager.confirm({
		title: '提示',
		msg: '该接口模板已存在，是否生成新的模板？',
		fn: function(r) {
			if (r) {
				saveTemplate(params)
			}
		}
	});
}
/**
 * 保存模板
 * @param  {[type]} params [description]
 * @return {[type]}        [description]
 */
function saveTemplate(params) {
	$.messager.prompt({
		title: 'Prompt',
		msg: `输入模板名称(默认名称为“${params.name}”)`,
		fn(r) {
			console.log('r', r)
			if (r !== undefined) {
				params.name = r || params.name
				reqPost('/ult/template/add', params).then(result => {
					let {
						insertId,
						message,
					} = result
					let msg = message || '设置模板成功！'
					$.messager.alert({
						title: "提示",
						msg,
					})
				})
			}
		}
	})
}